﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ReaderWriterLockSlimDemo
{
    class Program
    {
        private static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();
        static void Main(string[] args)
        {
            List<Task> lstTask = new List<Task>();
            for (int i = 0; i < 10; i++)
            {
                if (i % 5 != 0)
                {
                    var t = Task.Factory.StartNew(ReadSomething);
                    lstTask.Add(t);
                }
                else
                {
                    var t = Task.Factory.StartNew(WriteSomething);
                    lstTask.Add(t);
                }
            }
            Task.WaitAll(lstTask.ToArray());

            Console.ReadKey();
        }
        static public void ReadSomething()
        {
            rwl.EnterReadLock();
            try
            {
                Console.WriteLine("{0} Thread ID {1} 进入读取", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode());
                Thread.Sleep(1000);//模拟读取信息
                Console.WriteLine("{0} Thread ID {1} 读取完毕", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode());
            }
            finally
            {
                rwl.ExitReadLock();
            }
        }
        static public void WriteSomething()
        {
            rwl.EnterWriteLock();
            try
            {
                Console.WriteLine("{0} Thread ID {1} 开始写入", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode());
                Thread.Sleep(10000);//模拟写入信息
                Console.WriteLine("{0} Thread ID {1} 写入完毕", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode());
            }
            finally
            {
                rwl.ExitWriteLock();
            }
        }
    }
}
